<script setup>
import {computed} from "vue";
import { RouterView } from 'vue-router'
// 引入登录组件
import LoginView from "./views/LoginView.vue"
import MenuList from "./components/MenuList.vue"
import UserCard from "./components/UserCard.vue"
// 引入登录请求功能
import { loginApi } from "@/api/user.js"
import { getTeams } from "@/api/team.js"

// 引入并创建用户信息状态对象
import {useUserStore, useTeamStore} from "./stores/counter";
const userStore = useUserStore();
const teamStore = useTeamStore();

// 根据状态管理器中的状态，创建响应式数据
const userMsg = computed(()=>{
  return userStore.userMsg;
})

// 自定义事件的事件处理函数（用来接收子组件发送的数据）
async function loginFn(un, pw){
  // 发起登录请求
  const loginRes = await loginApi(un, pw);
  const loginData = loginRes.data;
  // 根据响应数据，做出登录后的处理
  if(loginData.code === 0){
    // 处理用户信息
    const um = {
      token: loginData.data.token,
      username: loginData.data.username,
      uId: loginData.data.uId,
      power: loginData.data.power,
      avatar: loginData.data.avatar
    }
    ElMessage({
      showClose: true,
      message: '登录成功，正在跳转',
      type:"success",
      onClose:()=>{
        // 持久化存储状态
        localStorage.setItem("userMsg", JSON.stringify( um ));
        // 修改状态管理器中的用户信息状态
        userStore.change_userMsg(um);
      }
    })

    // 筛选权限，只有超管才能获取所有部门，才能添加用户信息
    if(loginData.data.power !== 0) return;

    const teamRes = await getTeams(loginData.data.token);
    const teamData = teamRes.data;
    // 处理部门信息
    const arr = [];
    teamData.data.forEach(val=>{
      arr.push({
        tId: val.tId,
        tName: val.tName
      })
    })
    localStorage.setItem("teamMsg", JSON.stringify(arr));
    teamStore.change_teamMsg(arr);

    
  }else{
    ElMessage({
      showClose: true,
      message: loginData.msg,
      type:"error"
    })
  }
}

</script>

<template>
  <div class="common-layout" v-if="userMsg.token">
    <el-container>
      <el-header>
        <div>LOGO</div>
        <UserCard></UserCard>
      </el-header>
      <el-container>
        <el-aside class="menuListBox" width="200px">
          <MenuList></MenuList>
        </el-aside>
        <el-main>
          <Suspense><RouterView /></Suspense>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <LoginView v-else @login="loginFn"></LoginView>
</template>

<style>
.el-header{
  text-align: center;
  background: #428bca;
  display:flex;
  align-items:center;
  justify-content: space-between;
}

.menuListBox .el-row{
  display: block;
}
.menuListBox .el-row .el-col-12{
  max-width: 100%;
}

.el-container{
  width:100%;
}

.el-aside a{
  display:block
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

</style>
